import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

class Player {
	public DatagramSocket socket;
	public int id;
	public String name;
	public InetAddress ipAddress;
	public int client_port;
	public float x, y, rotation;
	private byte[] receiveData;
	private byte[] bullets;
	public Player(InetAddress ip, int id) {
		this.ipAddress = ip;
		this.id = id;
		this.client_port = 12000 + id;
		this.receiveData = new byte[1024];
		this.bullets = new byte[16*3*4]; //16 x 3 floats (x,y,rot);
		spawnListenerThread();
	}
	
	public void spawnListenerThread() {
		Thread one = new Thread() {
		    public void run() {
		        try {
		        	boolean done = false;
					long delta = 0;	
					long start = System.currentTimeMillis();
		        	socket = new DatagramSocket(client_port - 1000);
		    		while (!done) {
			    			if (delta >= 3) {
				    			DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
								socket.receive(receivePacket);
								processPacket();
			    			}
						long end = System.currentTimeMillis();
						delta = end - start;
						//Thread.sleep(5);
		    		}
		        } catch (SocketException e) {
					e.printStackTrace();
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		        finally {
		        	socket.close();
		        }
		    }

			private void processPacket() {								
				x = ByteBuffer.wrap(receiveData, 4, 4).order(ByteOrder.BIG_ENDIAN).getFloat();
			    y = ByteBuffer.wrap(receiveData, 8, 4).order(ByteOrder.BIG_ENDIAN).getFloat();	
			    rotation = ByteBuffer.wrap(receiveData, 12, 4).order(ByteOrder.BIG_ENDIAN).getFloat();	
				
			    //Read bullets (max 16 bullets!) 3*sizeof(float)*16
			     ByteBuffer.wrap(receiveData, 16, 192).get(bullets);

				//System.out.println("Received position packet from Player " + id + " position: " + Float.toString(x) + " : " + Float.toString(y));
				
			}  
		};
		one.start();
	}

	
	public byte[] getBullets(){
		return bullets;
	}
	
}